package me.imvc.app.controllers;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

import javax.servlet.http.HttpServletResponse;

import me.imvc.app.entities.Files;
import me.imvc.app.models.system.FileModel;
import me.imvc.core.BaseController;
import me.imvc.lib.Folder;
import me.imvc.lib.StringToMd5;

public class FilesController extends BaseController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// 附件上传
	private File fileData;
	private String fileDataFileName;
	private String fileDataContentType;
	// 编辑器文件上传
	private File filedata;
	private String filedataFileName;
	private String filedataContentType;

	private String folder;
	private FileModel fileModel;
	private String fileCode;

	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public String getFiledataFileName() {
		return filedataFileName;
	}

	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}

	public String getFiledataContentType() {
		return filedataContentType;
	}

	public void setFiledataContentType(String filedataContentType) {
		this.filedataContentType = filedataContentType;
	}

	public String getFileCode() {
		return fileCode;
	}

	public void setFileCode(String fileCode) {
		this.fileCode = fileCode;
	}

	public FileModel getFileModel() {
		return fileModel;
	}

	public void setFileModel(FileModel fileModel) {
		this.fileModel = fileModel;
	}

	public File getFileData() {
		return fileData;
	}

	public void setFileData(File fileData) {
		this.fileData = fileData;
	}

	public String getFileDataFileName() {
		return fileDataFileName;
	}

	public void setFileDataFileName(String fileDataFileName) {
		this.fileDataFileName = fileDataFileName;
	}

	public String getFileDataContentType() {
		return fileDataContentType;
	}

	public void setFileDataContentType(String fileDataContentType) {
		this.fileDataContentType = fileDataContentType;
	}

	public String getFolder() {
		return folder;
	}

	public void setFolder(String folder) {
		this.folder = folder;
	}

	public String getFileName() {
		return getFileDataFileName().substring(0,
				getFileDataFileName().indexOf("."));
	}

	public String getSuffix() {
		return getFileDataFileName().substring(
				getFileDataFileName().indexOf("."),
				getFileDataFileName().length());
	}

	public long getLength() {
		return getFileData().length();
	}

	@Override
	public String index() {
		int fileint = getFileModel().getHt()
				.find("from Files where code=?", getFileCode()).size();
		String str = null;
		if (fileint == 1) {
			Files fileBean = (Files) getFileModel().getHt()
					.find("from Files where code=?", getFileCode()).iterator()
					.next();

			try {
				HttpServletResponse response = getHttpServletResponse();
				String path = getRootPath() + fileBean.getDirectory()
						+ File.separator + fileBean.getCode();
				// 以流的形式下载文件。
				InputStream inputStream = new BufferedInputStream(
						new FileInputStream(path));
				byte[] buffer = new byte[inputStream.available()];
				inputStream.read(buffer);
				inputStream.close();
				// 清空response
				response.reset();
				// 设置response的Header
				String fileName = fileBean.getName() + fileBean.getSuffix();
				response.setHeader("Content-Type", fileBean.getType());
				response.addHeader("Content-Disposition",
						"attachment;filename="
								+ new String(fileName.getBytes("GBK"), "ISO8859-1"));
				response.addHeader("Content-Length", "" + fileBean.getSize());
				OutputStream outputStreamt = response.getOutputStream();
				outputStreamt.write(buffer);
				outputStreamt.flush();
				outputStreamt.close();
			} catch (IOException ex) {
			}

		} else {
			str = errorMsg("找不到该文件");
		}
		return str;
	}

	@Override
	public String show() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String editNew() {

		return null;
	}

	@Override
	public String create() {
		if (getFiledata() != null) {
			String textJson="{\"err\":\"上传失败\",\"msg\":\"\"}";
			try {
				java.util.Date date = new java.util.Date();
				java.sql.Timestamp timestamp = new java.sql.Timestamp(
						date.getTime());
				String fileCode = StringToMd5.encode(timestamp.toString()
						+ String.valueOf(getFiledata().length())
						+ getLoginName());
				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH) + 1;
				String str_month = month > 8 ? String.valueOf(month + 1) : "0"
						+ String.valueOf(month);
				setFolder("/attachments/xheditor/" + String.valueOf(year)
						+ str_month);
				String folderPath = getRootPath() + getFolder();
				Folder.newFolder(folderPath);
				InputStream inputStream = new FileInputStream(getFiledata());
				OutputStream outputStream = new FileOutputStream(folderPath
						+ File.separator + fileCode);
				byte buffer[] = new byte[2048];
				int count = 0;
				while ((count = inputStream.read(buffer)) > 0) {
					outputStream.write(buffer, 0, count);
				}
				outputStream.close();
				inputStream.close();
				java.util.Date date2 = new java.util.Date();
				java.sql.Timestamp timestamp2 = new java.sql.Timestamp(
						date2.getTime());
				getFileModel().setFile(new Files());
				getFileModel().getFile().setCode(fileCode);
				getFileModel().getFile().setName(
						getFiledataFileName().substring(0,
								getFiledataFileName().indexOf(".")));
				getFileModel().getFile().setDirectory(getFolder());
				getFileModel().getFile().setSize(getFiledata().length());
				getFileModel().getFile().setSuffix(
						getFiledataFileName().substring(
								getFiledataFileName().indexOf("."),
								getFiledataFileName().length()));
				getFileModel().getFile().setType(getFiledataContentType());
				getFileModel().getFile().setCreatedAt(timestamp);
				getFileModel().getFile().setUpdatedAt(timestamp2);
				getFileModel().save();
				getHttpServletResponse().setContentType("text/html;charset=UTF-8");
				textJson="{\"err\":\"\",\"msg\":\"" + getWebUrl()+ "/files?fileCode=" + getFileModel().getFile().getCode()+ "\"}";
			} catch (IOException e) {
				getHttpServletResponse().setContentType("text/html;charset=UTF-8");
			}
			try {
				getHttpServletResponse().getWriter().write(textJson);
			} catch (IOException e) {
				e.printStackTrace();
			}			
			return null;

		} else {
			try {
				java.util.Date date = new java.util.Date();
				java.sql.Timestamp timestamp = new java.sql.Timestamp(
						date.getTime());
				String fileCode = StringToMd5.encode(timestamp.toString()
						+ String.valueOf(getLength()) + getFileName()
						+ getLoginName());
				String folderPath = getRootPath() + getFolder();
				Folder.newFolder(folderPath);
				InputStream inputStream = new FileInputStream(getFileData());
				OutputStream outputStream = new FileOutputStream(folderPath
						+ File.separator + fileCode);
				byte buffer[] = new byte[2048];
				int count = 0;
				while ((count = inputStream.read(buffer)) > 0) {
					outputStream.write(buffer, 0, count);
				}
				outputStream.close();
				inputStream.close();
				java.util.Date date2 = new java.util.Date();
				java.sql.Timestamp timestamp2 = new java.sql.Timestamp(
						date2.getTime());
				getFileModel().setFile(new Files());
				getFileModel().getFile().setCode(fileCode);
				getFileModel().getFile().setName(getFileName());
				getFileModel().getFile().setDirectory(getFolder());
				getFileModel().getFile().setSize(getLength());
				getFileModel().getFile().setSuffix(getSuffix());
				getFileModel().getFile().setType(getFileDataContentType());
				getFileModel().getFile().setCreatedAt(timestamp);
				getFileModel().getFile().setUpdatedAt(timestamp2);
				getFileModel().save();
			} catch (IOException e) {
				getLoggerController().warn(
						"上传文件失败:" + getFileDataFileName() + ":"
								+ getFileDataContentType() + ":" + getLength());
				renderJson("{'statusCode':'300','message':'上传失败','fileName':'"
						+ getFileModel().getFile().getName() + "','fileCode':'"
						+ getFileModel().getFile().getCode()
						+ "','navTabId':'','callbackType':'','forwardUrl':''}");
			}
			return renderJson("{'statusCode':'200','message':'上传成功','fileName':'"
					+ getFileModel().getFile().getName()
					+ "','fileCode':'"
					+ getFileModel().getFile().getCode()
					+ "','navTabId':'','callbackType':'','forwardUrl':''}");
		}

	}

	@Override
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String destroy() {
		int fileint = getFileModel().getHt()
				.find("from Files where code=?", getFileCode()).size();
		String str = null;
		if (fileint == 1) {
			Files file = (Files) getFileModel().getHt()
					.find("from Files where code=?", getFileCode()).iterator()
					.next();
			getFileModel().delete(file);
			str = successMsg("删除成功");
		} else {
			str = errorMsg("删除失败找不到该文件");
		}
		return str;
	}

}
